package dao

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"log"
	"time"
	"ztool/common"
)

// Users 系统用户
type Users struct {
	ID        uint   //用户ID
	Username  string //用户名
	Password  string //密码md5
	CreatedAt time.Time
}

const defaultUserNameAndPwd = "admin"

// GetUserFromDB 从数据库查询用户
func GetUserFromDB(username *string) *Users {
	db := common.GetDB()

	var user Users
	db.Model(&Users{}).First(&user)

	return &user
}

// CreateDefaultUser 创建默认用户
func CreateDefaultUser() {

	//创建默认用户
	user := Users{
		ID:        1,
		Username:  defaultUserNameAndPwd,
		Password:  CreateSHA256(defaultUserNameAndPwd),
		CreatedAt: time.Now(),
	}
	CreatetUser(&user)
}

//CreatetUser 创建初始化用户
func CreatetUser(user *Users) {

	db := common.GetDB()

	//判断默认用户是否存在，不存在则创建
	var rows int64
	db.Model(&Users{}).Select("id").Count(&rows)

	if rows == 0 {
		//创建用户
		log.Printf("===========创建默认用户==========\r\n 用户名： %s \r\n 密码： %s", defaultUserNameAndPwd, defaultUserNameAndPwd)
		db.Create(&user)
		return
	}
}

//UpdateUserPwd 修改用户密码
func UpdateUserPwd(pwd string, username string) {
	db := common.GetDB()
	npwd := CreateSHA256(pwd)
	db.Model(&Users{}).Where("username = ?", username).Update("password", npwd)
}

//CreateSHA256 创建hmac sha256
func CreateSHA256(value string) string {
	mac := hmac.New(sha256.New, common.Secret)
	mac.Write([]byte(value))
	r := mac.Sum(nil)
	return hex.EncodeToString(r)
}
